package com.crazy.web.controller.user;

import cn.hutool.core.exceptions.ValidateException;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.crazy.enums.Constants;
import com.crazy.model.major.dto.RoleAuthorityDto;
import com.crazy.model.major.entity.TUserRole;
import com.crazy.model.major.service.TUserRoleService;
import com.crazy.rest.RestResult;
import com.crazy.web.controller.BaseController;
import com.crazy.web.service.user.RoleService;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zhaochaofeng
 * @version 1.0
 * @date 2020/12/15 11:38
 */
@Controller
@Log4j2
@RequestMapping("/user/role")
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private TUserRoleService tUserRoleService;

    @RequiresPermissions("role:view")
    @GetMapping("/view")
    public String View() {
        request.setAttribute("url", "/user/role/view");
        return "role/view";
    }

    @RequiresPermissions("role:list")
    @GetMapping("/list")
    @ResponseBody
    public RestResult list(@RequestParam int page, @RequestParam int rows) {
        IPage<TUserRole> roleIPage = roleService.list(page, rows);
        return RestResult.createSuccessResult("查询成功", roleIPage);
    }

    @RequiresPermissions("role:delete")
    @PostMapping("/delete")
    @ResponseBody
    public RestResult delete(@RequestParam Long id) {
        roleService.delete(id);
        return RestResult.createSuccessResult("删除成功");
    }

    @RequiresPermissions("authority:list")
    @GetMapping("/all")
    @ResponseBody
    public RestResult all(@RequestParam(required = false) Long roleId) {
        TUserRole tUserRole = null;
        if(roleId!=null){
            tUserRole = tUserRoleService.getById(roleId);
        }
        List<RoleAuthorityDto> list =  roleService.getAuthByRoleId(roleId);
        return RestResult.createSuccessResult("查询成功", list, tUserRole);
    }

    /**
     * @param id
     * @return
     */
    @RequiresPermissions("role:add")
    @PostMapping("/add")
    @ResponseBody
    public RestResult add(@RequestParam(required = false) Long id, @RequestParam String roleName, @RequestParam String requireRole
            , @RequestParam(required = false) String descript, @RequestParam(value="auths[]", required = false) Long[] auths) {
        TUserRole tUserRole = new TUserRole();
        tUserRole.setId(id);
        tUserRole.setRoleName(roleName);
        tUserRole.setRequireRole(requireRole);
        tUserRole.setDescript(descript);
        roleService.saveOrUpdate(tUserRole, auths);
        return RestResult.createSuccessResult("操作成功");
    }
}
